package com.qx.ddx.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.qx.ddx.R;
import com.qx.ddx.activity.adapter.CategoryAdapter;
import com.qx.ddx.activity.adapter.FragmentAdapter;
import com.qx.ddx.activity.fragment.OrderChooseFragment;
import com.qx.ddx.activity.fragment.OrderDetailFragment;
import com.qx.ddx.activity.fragment.OrderMyOrderFragment;
import com.qx.ddx.httprequest.CategoryRequest;
import com.qx.ddx.util.Constants;
import com.qx.ddx.util.FragmentInterface;
import com.qx.ddx.util.SpInfo;
import com.qx.ddx.util.Toast;
import com.qx.ddx.util.nohttp.CallServer;
import com.qx.ddx.util.nohttp.HttpArrayInterface;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/4/3.
 */
public class OrderActivity extends BaseFragmentActivity implements HttpArrayInterface<HashMap<String, String>>, FragmentInterface {
    public static final int Choose = 0;
    public static final int Detail = 1;
    public static final int MyOrder = 2;
    public boolean isChangeCategory = false;

    public CategoryAdapter categoryAdapter;

    private TextView table_label_num_txt, table_label_name_txt;
    private View table_label_layout;
    private FragmentAdapter fragmentAdapter;
    private boolean isFirst = true;
    private String categoryId;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        View view = findViewById(R.id.order_background);
        SharedPreferences sp = getSharedPreferences(SpInfo.Setting, Activity.MODE_PRIVATE);
        view.setBackgroundResource(sp.getInt(SpInfo.ThemeBg, R.color.set_background));
        table_label_num_txt = (TextView) findViewById(R.id.order_table_num);
        table_label_name_txt = (TextView) findViewById(R.id.order_table_name);
        table_label_layout = findViewById(R.id.order_table_label_Layout);
        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.menu_list);
        findViewById(R.id.layout_my_order_list).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerView.setClickable(false);
                recyclerView.setFocusable(false);
                fragmentAdapter.setFragment(MyOrder);
            }
        });
        categoryAdapter = new CategoryAdapter(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(categoryAdapter);
        List<Fragment> fragments = new ArrayList<Fragment>();
        fragments.add(new OrderChooseFragment());
        fragments.add(new OrderDetailFragment());
        fragments.add(new OrderMyOrderFragment());
        fragmentAdapter = new FragmentAdapter(this.getSupportFragmentManager(), R.id.order_content, fragments);
        if (savedInstanceState != null && savedInstanceState.containsKey("CurrentPage") == true) {//如果savedInstanceState不为空，用KEY值找到对应的EditText内容，填入EditText控件
            int CurrentPage = savedInstanceState.getInt("CurrentPage");
            fragmentAdapter.setFragment(CurrentPage);
        } else {
            fragmentAdapter.setFragment(Choose);
        }
        CategoryRequest CRequest = new CategoryRequest(this);
        CRequest.Connect(this);
    }

    protected void onResume() {
        super.onResume();
        SharedPreferences sp = getSharedPreferences(SpInfo.Setting,
                Activity.MODE_PRIVATE);
        String table_num_str = sp.getString(SpInfo.Table_Number, getResources().getString(R.string.tip_set));
        table_label_num_txt.setText(table_num_str);
        String table_name_str = sp.getString(SpInfo.Table_Name, "");
        table_label_name_txt.setText(table_name_str);
        String num_str = table_label_num_txt.getText().toString();
        if (num_str.equals(getResources().getString(R.string.tip_set))) {
            table_label_layout.setFocusable(true);
            table_label_layout.setClickable(true);
            table_label_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(OrderActivity.this, SetActivity.class);
                    OrderActivity.this.startActivity(intent);
                }
            });
        } else {
            table_label_layout.setFocusable(false);
            table_label_layout.setClickable(false);
        }
        if (fragmentAdapter.initAllTab()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        if (fragmentAdapter.getCurrentFragment().isVisible()) {
                            Intent intent = new Intent();
                            intent.putExtra("id", categoryAdapter.getSelectedItem().get("id"));
                            intent.setAction(SpInfo.BroadcastAction);
                            sendBroadcast(intent);
                            break;
                        }
                    }
                }
            }).start();
        }
    }

    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putInt("CurrentPage", fragmentAdapter.getCurrentPageIndex());
    }

    protected void onPause() {
        super.onPause();
        fragmentAdapter.removeAllTab();
        isChangeCategory = true;
    }

    public String getCategoryName() {
        HashMap<String, String> map = categoryAdapter.getSelectedItem();
        String categoryName = map.get("name");
        return categoryName;
    }

    @Override
    public void getData(int what, List<HashMap<String, String>> data, boolean success, String message) {
        switch (what) {
            case Constants.Category_List_Request_id:
                if (!success) {
                    Toast.show(R.mipmap.tips_warning, message);
                    return;
                }
                if (isFirst) {
                    isFirst = false;
                    String id = data.get(0).get("id");
                    categoryId = id;
                    Intent intent = new Intent();
                    intent.putExtra("id", id);
                    intent.setAction(SpInfo.BroadcastAction);
                    sendBroadcast(intent);
                }
                categoryAdapter.setData(data);
                categoryAdapter.setOnItemClickListener(new CategoryAdapter.onItemClickListener() {
                    @Override
                    public void onItemClick(String id, View v) {
                        Log.i("OrderActivity", "onItemClick id:" + id);
                        CallServer.getRequestInstance().cancelAll();
                        if (!categoryId.equals(id)) {
                            isChangeCategory = true;
                            categoryId = id;
                        }
                        fragmentAdapter.setFragment(Choose);
                        Intent intent = new Intent();
                        intent.putExtra("id", id);
                        intent.setAction(SpInfo.BroadcastAction);
                        sendBroadcast(intent);
                    }
                });
                break;
            default:
                break;
        }
    }

    @Override
    public void toAnotherFragment(int fromWhat, int toWhat, String id) {
        if (toWhat == this.Detail) {
            fragmentAdapter.setOrderDetailFragment(toWhat, id, categoryId);
        } else if (toWhat == -1) {
            fragmentAdapter.returnPrevious();
        } else {
            fragmentAdapter.setFragment(toWhat);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            int state = fragmentAdapter.getCurrentPageIndex();
            switch (state) {
                case Choose:
                    finish();
                    break;
                case Detail:
                    fragmentAdapter.setFragment(Choose);
                    break;
                case MyOrder:
                    fragmentAdapter.returnPrevious();
                    break;
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
